package cn.edu.nju.software.fantasyCard.screens;

/**
 *   创建者：            杨光 
 *   创建时间：        2014-2-22   下午5:02:47  
 */


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import cn.edu.nju.software.fantasyCard.MainGame;
import cn.edu.nju.software.fantasyCard.network.NetworkConnect;
import cn.edu.nju.software.fantasyCard.network.logic.LoginHandle;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;

public class LogInScreen implements Screen {

	MainGame mainGame;
	Stage stage;
	LoginHandle loginHandle;
	
	public LogInScreen(MainGame mainGame) {
		this.mainGame = mainGame;
		loginHandle = new LoginHandle(this);
	}
	
	@Override
	public void render(float delta) {
	    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
	    stage.act(Gdx.graphics.getDeltaTime());
	    stage.draw();
	}

	@Override
	public void resize(int width, int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void show() {
		// TODO Auto-generated method stub
		stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); 
		Gdx.input.setInputProcessor(stage);

		Table table = new Table();
		table.setFillParent(true);
		stage.addActor(table);
		
	    Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));
	    Label gameNameLabel = new Label("修仙卡牌RPG", skin);
	    Label userNameLabel = new Label("账号", skin);
	    TextField userNameText = new TextField("", skin);
	    userNameText.setName("username");
		Label pwdLabel = new Label("密码", skin);
		TextField pwdText = new TextField("", skin);	
		pwdText.setName("password");
		pwdText.setPasswordMode(true);
		pwdText.setPasswordCharacter('*');
		
		CheckBox rememberMeBox = new CheckBox("记住密码", skin);
		CheckBox autoLogInBox = new CheckBox("自动登陆", skin);
		TextureRegion upRegion = skin.getRegion("default-slider-knob");
		TextureRegion downRegion = skin.getRegion("default-slider-knob");
		BitmapFont buttonFont = skin.getFont("default-font");

		TextButton logInButton = new TextButton("登陆", skin);
		TextButton registerButton = new TextButton("注册", skin);
		logInButton.addListener(new InputListener() {
			public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
				String usernameString = ((TextField)stage.getRoot().findActor("username")).getText();
				String passwordString = ((TextField)stage.getRoot().findActor("password")).getText();
				
				//Mina
				NioSocketConnector connector = new NioSocketConnector();
				DefaultIoFilterChainBuilder chain = connector.getFilterChain();
				chain.addLast("strFilter",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
				connector.setHandler(loginHandle);
				connector.setConnectTimeoutCheckInterval(30);
				ConnectFuture connectFuture = connector.connect(new InetSocketAddress("localhost",9988));
//				connector.dispose();

//	            Socket client;
//				String request = usernameString+" "+passwordString;
//				Gdx.app.log("Fantasy Card", "username: "+usernameString+" password: "+passwordString);
//				try {
//					client = NetworkConnect.getSocket();
//					client.getOutputStream().write(request.getBytes());
//					String response = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
//					Gdx.app.log("Fantasy Card", "got server message: " + response);
//					if(response.equals("OK")) {
//						mainGame.setScreen(new MainMenuScreen(mainGame));
//					}
//				} catch (Exception e) {
//					Gdx.app.log("Fantasy Card", "an error occured", e);
//				} 
				
				
				return false;
			}
		});
		
		registerButton.addListener(new InputListener() {
			public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
				mainGame.setScreen(new RegisterScreen(mainGame));
				return false;
			}
		});
		
		table.debug();
		table.add(gameNameLabel).center();
		table.row();
		table.add(userNameLabel);
		table.add(userNameText);
		table.row();
		table.add(pwdLabel);
		table.add(pwdText);
		table.row();
		table.add(rememberMeBox);
		table.add(autoLogInBox);
		table.row();
		table.add(logInButton);
		table.add(registerButton);
	}

	@Override
	public void hide() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
		
	}

	public void logInSuccess() {
		mainGame.setScreen(new MainMenuScreen(mainGame));
	}
}
